package ArrayPackage2;

/**
 * @author Lzm
 * @version 1.0
 */
public class minSubArrayLen_ {
  public static void main(String[] args) {
    int[] nums = new int[]{2,3,1,2,4,3};
    int target = 7;
    int result = minSubArrayLen(target, nums);
    System.out.println(result);
  }

  // 双指针法
  public static int minSubArrayLen(int target, int[] nums) {
    if (nums == null || nums.length == 0){
    return 0;
    }
    int result = Integer.MAX_VALUE;
    int p = 0;
    int sum = 0;
    for (int i = 0; i < nums.length; i++) {
      // 1. 每次循环都令sum += nums[i]
      sum += nums[i];
      // 2. 当sum >= target时说明此时sum达到了target, 需要减元素来得到较小长度的子数组
      while(sum >= target){
        sum -= nums[p];
        // 3. 注意这里是i - p + 1; 先取result 后令p++;
        result = Math.min(i - p + 1,result);
        p++;
      }
    }
    return result == Integer.MAX_VALUE ? 0 : result;
  }
}
